/**
* 实名认证
*/
import React, { Component } from 'react';
import { View, StyleSheet, Text, Image, TouchableOpacity, PermissionsAndroid } from "react-native";
import { connect } from 'react-redux';
import { Colors, Dimens, ImageRes } from '../../utils/Assets';
import { create_service } from '../../redux/index.js';
import { Contract } from '../../service/index.js';
import ImagePicker from 'react-native-image-picker'
import { Actions } from 'react-native-router-flux';
import Toast from 'react-native-root-toast';
import { ProgressView, CardSwiper } from '../custom/index'
import { getStore } from '../../redux/index.js';
import ActionSheet from 'react-native-actionsheet'
import RNFetchBlob from 'rn-fetch-blob'
import CameraRoll from "@react-native-community/cameraroll";
class PersonalShareImageView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            selectedImage: ""
        }
        this.userInfo = getStore().getState().auth.userInfo
    }
    componentDidMount() {
        this.getImageData()
    }
    getImageData() {
        this.setState({ loading: true })
        this.props.dispatch(create_service(Contract.POST_USER_SHARE_IMAGE, { token: this.userInfo.token }))
            .then(res => {
                if (res) {
                    this.iamgeData = res
                }
                this.setState({ loading: false })
            })
    }
    onLongPress(rowData) {
        this.setState({ selectedImage: rowData.path }, () => {
            this.ActionSheet.show()
        })
    }
    renderImageRow(rowData) {
        return (
            <Image source={{ uri: rowData.path }} style={{ width: Dimens.DeviceWidth * 0.8, height: (Dimens.DeviceWidth - 80) * 2, alignSelf: 'center', marginTop: 20, resizeMode:'contain' }}></Image>
        )
    }
    async requestReadPermission() {
        try {
            //返回string类型
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限
                    'title': '我要读写权限',
                    'message': '没权限我不能工作，同意就好了'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                this.saveImageAlbum(this.state.selectedImage)
            } else {

            }
        } catch (err) {

        }
    }
    saveImageAlbum(imageUrl) {
        if (imageUrl.length > 0) {
            RNFetchBlob.config({
                fileCache: true,
                appendExt: 'png'
            }).fetch('GET', imageUrl, {})
                .then((res) => {
                    CameraRoll.saveToCameraRoll(res.path()).then(() => {
                        Toast.show('保存成功', { position: Toast.positions.CENTER })
                        this.deleteCacheImage(res.path());
                    }).catch((err) => {
                        this.deleteCacheImage(res.path());
                    });
                })
        }
    }
    deleteCacheImage(path) {
        RNFetchBlob.fs.unlink(path).then(() => { })
    }
    render() {
        return (
            <View style={styles.container}>
                {this.iamgeData && <CardSwiper style={{ width: Dimens.DeviceWidth, height: (Dimens.DeviceHeight - 120), }}
                    dataSource={this.iamgeData}
                    width={Dimens.DeviceWidth}
                    height={(Dimens.DeviceHeight - 120)}
                    renderRow={this.renderImageRow}
                    onPress={this.onPressRow}
                    loop={false}
                    onLongPress={(rowData) => {
                        this.onLongPress(rowData)
                    }}
                    ratio={0.8}
                />}
                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    options={['保存图片', '取消']}
                    cancelButtonIndex={1}
                    destructiveButtonIndex={1}
                    onPress={(index) => {
                        if (index === 0) {
                            if (Dimens.isAndroid) {
                                const granted = PermissionsAndroid.check(
                                    PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
                                )
                                granted.then((data) => {
                                    if (data) {
                                        this.saveImageAlbum(this.state.selectedImage)
                                    } else {
                                        this.requestReadPermission()
                                    }
                                })
                            }
                            else {
                                this.saveImageAlbum(this.state.selectedImage)
                            }
                        }
                    }}
                />
                <ProgressView show={this.state.loading} />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Colors.white_color
    }
});
const ExportView = connect()(PersonalShareImageView);
module.exports.PersonalShareImageView = ExportView
